package org.example.utils.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class JwtUtil {

    private static String secret= "NjYwQ0Y0N0M3ODhFODYwOUU2RDM1RTNDRkNENjQ1REE=";
    private static long expire= 3600;
    private String header="token";
    public static String getLongTimeToken(String phone){
        Date nowDate = new Date();
        //过期时间  两天后的这个点
        Date expireDate = new Date(nowDate.getTime() + expire * 1000 * 47);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(phone)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    //一分钟后过期
    public static String getShortTimeToken(String phone){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire*100 );
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(phone)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
	//刷新Token
    public static Map refresh(String phone){
        Map<String,String> map = new HashMap<>();
        try{
            String shortTimeToken = getShortTimeToken(phone);
            String longTimeToken = getLongTimeToken(phone);
            map.put("short",shortTimeToken);
            map.put("long",longTimeToken);
        }catch (Exception e){
            System.out.println("长期token过期，请重新登录");
            map.put("202","请重新登录");
        }
        return map;
    }

    /*
     * 获取 Token 中注册信息
     */
    public static Claims getTokenClaim(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
